<template>
  <div class="app-container split-layout">
    <!-- 左侧文件列表 -->
    <div class="left-panel">
      <el-card>
        <div slot="header">
          <h3>课程资料列表</h3>
        </div>
        <ul class="file-list">
          <li
            v-for="(file, index) in processedFiles"
            :key="index"
            @click="previewFile(file)"
            :class="{ active: activeFile === file.fullPath }">
            <i class="el-icon-document"></i>
            {{ file.displayName }}
          </li>
        </ul>
      </el-card>
    </div>

    <!-- 右侧PDF预览 -->
    <div class="right-panel">
      <el-card>
        <div slot="header">
          <h3>文件预览</h3>
        </div>
        <iframe
          v-if="previewUrl"
          :src="previewUrl"
          class="pdf-preview"></iframe>
        <div v-else class="empty-tip">请选择左侧文件进行预览</div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getFileList } from "@/api/class/class_choose";

export default {
  name: "StudyMaterials",
  data() {
    return {
      fileList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      activeFile: null, // 添加 activeFile
      previewUrl: null  // 添加 previewUrl
    };
  },
  mounted() {
    this.fetchFileList();
  },
  methods: {
    // 获取文件列表
    async fetchFileList() {
      try {
        const classId = this.$route.query.classId;
        const response = await getFileList(classId);
        if (response.code === 200) {
          this.fileList = response.rows.map(file => ({
            ...file,
            fileName: this.extractFileName(file.class_file)
          }));
        }
      } catch (error) {
        console.error("获取文件列表失败:", error);
        this.$message.error("文件加载失败");
      }
    },

    // 下载文件
    downloadFile(relativePath) {
      const fullUrl = `${this.baseUrl}${relativePath}`;
      window.open(fullUrl, '_blank');
    },

    // 提取文件名
    extractFileName(fullPath) {
      // 获取文件名（包括扩展名）
      let fileName = fullPath.split(/[\\/]/).pop();

      // 找到第一个下划线的位置
      const underscoreIndex = fileName.indexOf('_');

      // 如果找到下划线，截取下划线前的部分；否则返回完整文件名
      if (underscoreIndex > -1) {
        return fileName.substring(0, underscoreIndex);
      } else {
        return fileName;
      }
    },


    // 返回课程选择页
    handleClose() {
      this.$router.push('/class/choose');
    },

    // 处理带逗号分隔的文件路径
    processFiles() {
      return this.fileList.flatMap(file =>
        file.class_file.split(',').map(path => {
          const trimmedPath = path.trim();
          return {
            fullPath: trimmedPath,
            displayName: this.extractFileName(trimmedPath)
          };
        })
      );
    },

    // 预览文件
    previewFile(file) {
      this.activeFile = file.fullPath;
      this.previewUrl = `${this.baseUrl}${file.fullPath}`;
    }
  },
  computed: {
    processedFiles() {
      return this.processFiles();
    }
  }
}
</script>

<style scoped>
.split-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

.left-panel {
  width: 320px;
  min-width: 320px;
}

.right-panel {
  flex: 1;
}

.file-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.file-list li {
  padding: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  border-radius: 4px;
}

.file-list li:hover {
  background-color: #f5f7fa;
}

.file-list li.active {
  background-color: #409EFF20;
  color: #409EFF;
}

.el-icon-document {
  margin-right: 8px;
  font-size: 18px;
}

.pdf-preview {
  width: 100%;
  height: 750px;
  border: none;
}

.empty-tip {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}
.box-card {
  min-height: 500px;
}
.el-icon-document {
  color: #409EFF;
}
</style>
